﻿/*****************************************
 * File Name:   AjaxContentLoader.js
 * Author:      Chen Xin
 * Version:     1.0
 * Date:        2006-09-18
 * Description: Ajax 异步调用框架类
 *****************************************/
 
 var Net = new Object();

 Net.READY_STATE_UNINITIALIZED = 0;
 Net.READY_STATE_LOADING = 1;
 Net.READY_STATE_LOADED = 2;
 Net.READY_STATE_INTERACTIVE = 3;
 Net.READY_STATE_COMPLETE = 4;

 Net.ContentLoader = function(url, onLoad, onError, method, params, contentType) {
    this.url = url;
    this.onLoad = onLoad;
    this.onError = (onError) ? onError : this.defaultError;
    this.request = null;
    this.loadXMLDoc(url, method, params, contentType);
    Net.currentLoader = this;
 }
 
 Net.ContentLoader.prototype = {
    loadXMLDoc : function(url, method, params, contentType) {
        if (!method) {
            method = "GET";
        }
        if (!contentType && method == "POST") {
            contentType='application/x-www-form-urlencoded';
        }
        if (window.XMLHttpRequest) {
            this.request = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            this.request = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (this.request) {
            try {
                var loader = this;
                this.request.onreadystatechange = function() {
                    loader.onReadyState.call(loader);//
                }
                this.request.open(method, url, true);
                if (contentType) {
                    this.request.setRequestHeader('Content-Type', contentType);
                }
                this.request.send(params);
            }
            catch (err) {
                this.onError.call(this);
            }
        }
    },
    onReadyState : function() {
        var request = this.request;
        var ready = request.readyState;
        if (ready == Net.READY_STATE_COMPLETE) {
            var httpStatus = request.status;
            if (httpStatus == 200 || httpStatus == 0) {
                this.onLoad.call(this);
            } else {
                this.onError.call(this);
            }
        }
    },
    defaultError : function() {
        alert("程序异步调用出现错误，请重新运行\n" + 
            "如再出现错误，请检查您的操作或联系管理员！\n" + 
            "\nreadyState:" + this.request.readyState + 
            "\nstatus:" + this.request.status + 
            "\nheaders:" + this.request.getAllResponseHeaders());
    }
 }